package ch.supsi.gavdat.elevator;

import java.util.Map;

import ch.supsi.gavdat.elevator.handler.Elevator;
import ch.supsi.web.HandlerSetup;
import ch.supsi.web.Request;
import ch.supsi.web.Server;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.config.EmbeddedConfiguration;

public class ElevatorServer implements HandlerSetup {
	
	private static final String DBFILE = "elevator.db";
	
	private ObjectContainer rootContainer;
	
	public static void main(String[] args) throws Exception
    {
		Server server = new Server();
        ElevatorServer elevatorServer = new ElevatorServer();
		server.Start(8080, elevatorServer, new Elevator(), elevatorServer);
    }

	@Override
	public void init() {
		EmbeddedConfiguration configuration = Db4oEmbedded.newConfiguration();
		configuration.common().updateDepth(999);
		configuration.common().activationDepth(999);
		//configuration.file().lockDatabaseFile(false);
		rootContainer = Db4oEmbedded.openFile(configuration, DBFILE);
	}
	
	@Override
	public void preHandle(Request request) {
		ObjectContainer db = rootContainer.ext().openSession();
		request.setAttribute("db", db);
	}

	@Override
	public void postHandle(Request request) {
		ObjectContainer db = (ObjectContainer) request.getAttribute("db");
		db.close();
	}

	@Override
	public void manageMap(Map<String, Object> map, Request request) {
		map.put("request", request);
	}
	
}
